package com.wormhole.wormholemanagement.controller;

import cn.hutool.core.util.StrUtil;
import com.wormhole.wormholemanagement.dto.NewsPhotoDTO;
import com.wormhole.wormholemanagement.entity.NewsPhoto;
import com.wormhole.wormholemanagement.service.NewsPhotoService;
import com.wormhole.wormholemanagement.utils.SpecificationBuilder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 新闻照片管理控制器，提供新闻照片的增删改查、搜索、归档、导入等操作。
 * 所有接口均通过Swagger进行文档化，便于前后端协作和接口调试。
 */
@RestController
@RequestMapping("/api/news-photos")
@Tag(name = "新闻照片管理", description = "新闻照片管理相关接口")
public class NewsPhotoController {
    private static final String TREE_CACHE_KEY = "photo_tree_cache";
    private final NewsPhotoService photoService;

    @Autowired
    public NewsPhotoController(NewsPhotoService photoService) {
        this.photoService = photoService;
    }

    /**
     * 创建新闻照片
     *
     * @param photo       新闻照片对象，包含照片的基本信息
     * @param operatorId  操作员ID，用于记录谁执行了该操作
     * @return 创建成功的新闻照片对象
     */
    @PostMapping
    @Operation(summary = "创建新闻照片", description = "创建一条新的新闻照片记录")
    public ResponseEntity<NewsPhoto> createPhoto(@RequestBody NewsPhoto photo,
                                                 @RequestParam Long operatorId) {
        NewsPhoto createdPhoto = photoService.createPhoto(photo, operatorId);
        return ResponseEntity.ok(createdPhoto);
    }

    /**
     * 更新新闻照片
     *
     * @param id          照片ID，指定要更新的照片
     * @param photo       更新后的照片对象
     * @param operatorId  操作员ID
     * @return 更新后的新闻照片对象
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新新闻照片", description = "根据ID更新新闻照片信息")
    public ResponseEntity<NewsPhoto> updatePhoto(@PathVariable Long id,
                                                 @RequestBody NewsPhoto photo,
                                                 @RequestParam Long operatorId) {
        NewsPhoto updatedPhoto = photoService.updatePhoto(id, photo, operatorId);
        return ResponseEntity.ok(updatedPhoto);
    }

    /**
     * 删除新闻照片
     *
     * @param id          照片ID，指定要删除的照片
     * @param operatorId  操作员ID
     * @return HTTP状态码204（无内容）
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除新闻照片", description = "根据ID删除新闻照片")
    public ResponseEntity<Void> deletePhoto(@PathVariable Long id, @RequestParam Long operatorId) {
        photoService.deletePhoto(id, operatorId);
        return ResponseEntity.noContent().build();
    }

    /**
     * 获取新闻照片详情
     *
     * @param id 照片ID
     * @return 指定ID的新闻照片对象
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取新闻照片详情", description = "根据ID获取新闻照片详细信息")
    public ResponseEntity<NewsPhoto> getPhotoById(@PathVariable Long id) {
        NewsPhoto photo = photoService.getPhotoById(id);
        return ResponseEntity.ok(photo);
    }

    /**
     * 获取新闻照片列表（分页）
     *
     * @param pageable 分页参数，默认每页10条记录
     * @return 分页后的新闻照片列表
     */
    @GetMapping
    @Operation(summary = "获取新闻照片列表", description = "分页获取新闻照片列表")
    public ResponseEntity<Page<NewsPhoto>> getAllPhotos(
            @PageableDefault(size = 10) Pageable pageable) {
        Page<NewsPhoto> photos = photoService.getAllPhotos(pageable);
        return ResponseEntity.ok(photos);
    }

    /**
     * 搜索新闻照片（分页）
     *
     * @param params   搜索条件参数
     * @param pageable 分页参数
     * @return 符合条件的新闻照片列表（分页）
     */
    @Transactional(readOnly = true)
    @GetMapping("/search")
    @Operation(summary = "搜索新闻照片", description = "根据条件搜索新闻照片，支持分页")
    public ResponseEntity<Page<NewsPhotoDTO>> searchPhotos(
            @RequestParam Map<String, String> params,
            @PageableDefault(size = 10) Pageable pageable) {

        Specification<NewsPhoto> spec = SpecificationBuilder.buildSpecification(params);
        String page = params.get("page");
        Integer pageNo = StrUtil.isAllEmpty(page) ? 0 : Integer.parseInt(page);
        String size = params.get("size");
        Integer pageSize = StrUtil.isAllEmpty(size) ? 10 : Integer.parseInt(size);
        pageable = PageRequest.of(pageNo, pageSize);

        Page<NewsPhoto> records = photoService.searchPhotos(spec, pageable);
        Page<NewsPhotoDTO> dtoPage = records.map(NewsPhotoDTO::fromEntity);
        return ResponseEntity.ok(dtoPage);
    }

    /**
     * 批量更新新闻照片的归档状态
     *
     * @param photoIds         照片ID列表
     * @param isMovedToArchive 是否归档
     * @return 更新成功的记录数
     */
    @PutMapping("/batch-archive")
    @Operation(summary = "批量更新归档状态", description = "批量更新新闻照片的归档状态")
    public int batchUpdateArchiveStatus(@RequestParam List<Long> photoIds,
                                        @RequestParam Boolean isMovedToArchive) {
        return photoService.batchUpdateArchiveStatus(photoIds, isMovedToArchive);
    }

    /**
     * 批量移动照片到不移管
     * @param photoIds
     */
    @PutMapping("/batch-move-archive")
    @Operation(summary = "批量移动照片到不移管", description = "批量移动照片到不移管")
    @CacheEvict(value = TREE_CACHE_KEY, allEntries = true)
    public void batchMoveArchive(@RequestParam List<Long> photoIds,@RequestParam Integer moveType) {
        photoService.batchMoveArchive(photoIds,moveType);
    }

    /**
     * 导入新闻照片
     *
     * @param path 照片路径
     */
    @PostMapping("/importPhoto")
    @Operation(summary = "导入照片", description = "从指定路径导入照片")
    @CacheEvict(value = TREE_CACHE_KEY, allEntries = true)
    public void importPhoto(@RequestParam(value = "path", required = true) String path) {
        this.photoService.importPhoto(path);
    }

    /**
     * 重命名文件夹
     *
     * @param oldPath      原文件夹路径
     * @param newFolderName 新文件夹名称
     * @return 是否重命名成功
     */
    @PostMapping("/rename-folder")
    @Operation(summary = "重命名文件夹", description = "重命名指定路径的文件夹")
    public ResponseEntity<Boolean> renameFolder(
            @RequestParam String oldPath,
            @RequestParam String newFolderName) {
        boolean isRenamed = photoService.renameFolder(oldPath, newFolderName);
        return ResponseEntity.ok(isRenamed);
    }

    /**
     * 下载压缩文件
     *
     * @param response  HTTP响应对象
     */
    @GetMapping("/downloadZip")
    @Operation(summary = "下载压缩文件", description = "下载指定单位和年份的压缩文件")
    public void downloadZip(HttpServletResponse response,String downloadType,@RequestParam Map<String, String> params,
                            @PageableDefault(size = 10) Pageable pageable ) {

        photoService.downloadZip(response,downloadType, params,pageable);
    }

    @PostMapping("/importExcel")
    @Operation(summary = "导入档案数据", description = "从Excel文件导入档案数据")
    public void importExcel( @RequestPart("file") MultipartFile file){
        photoService.importExcel(file);
    }

    @PostMapping("/genFileNumber")
    @Operation(summary = "重新编排档号", description = "重新编排档号")
    @CacheEvict(value = TREE_CACHE_KEY, allEntries = true)
    public void genFileNumber(@RequestParam String path){
        photoService.genFileNumber(path);
    }


}
